package com.atsmart.app.activity;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.Toast;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.exception.GlobalExceptionHandler;
import com.atsmart.app.utils.DialogUtil;

/**
 * 程序进入后台调用onStop() 重新进入前台调用onResume()
 * 只有一个activity处于活动状态，activity是栈的概念
 * @author yhl 
 * 2013-11-4上午11:14:43 
 * TODO
 */
public class BaseActivity extends Activity {
	private static Dialog dialog = null;
    protected boolean bRetryRequire_;
    private int iLatestErrorCode_;
    
    private static final String TAG = BaseActivity.class.getName();

    protected  ArrayList<Object> loadStatus;//只是管理当前activity
    protected  HashSet<Object> arrTaskFailed_; //异步任务请求失败

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        GlobalExceptionHandler.register(this);
        bRetryRequire_ = false;
        iLatestErrorCode_ = 0;
        loadStatus = new ArrayList<Object>();
    }

    @Override
    protected void onResume() {
        super.onResume();
        BizApp.getInstance().setCurrentActivity(this);
        
		// if (!isActive) {
		// app 从后台唤醒，进入前台
		// isActive = true;
		// }
	}

    @Override
    protected void onStop() {
		super.onStop();
		if (!isAppOnForeground()) {
			// app 进入后台
			// 全局变量isActive = false 记录当前已经进入后台
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		if (intent != null) {
			if (intent.getFlags() == Intent.FLAG_ACTIVITY_CLEAR_TOP) {
				// quit application now?
				if (intent.getBooleanExtra("ExitNow", true)) {
					this.finish();
					return;
				}
			}
		}
	}

    @Override
    protected void onPause() {
    	hideLoading();
        super.onPause();
    }

    protected Dialog showLoading() {
        if (dialog == null) {
            dialog = DialogUtil.getLoadingDialog(this);
            dialog.show();
        }
        return dialog;
    }
    
    protected Dialog showLoading(String message) {
        if (dialog == null) {
            dialog = DialogUtil.getLoadingDialog(this,message);
            dialog.show();
        }
        return dialog;
    }
    
    
    

    protected void hideLoading() {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }

    protected synchronized void registerLoadStatus(Object obj) {
        if (!loadStatus.contains(obj)) {
            loadStatus.add(obj);
        }
    }

    protected synchronized boolean IsLoadingOrFailed(Object obj) {
        return arrTaskFailed_!= null && arrTaskFailed_.contains(obj);
    }

    protected synchronized void loadingFailed(Object obj, int iErrorCode) {
        if (this.arrTaskFailed_ == null){
            this.arrTaskFailed_ = new HashSet<Object>();
        }
        this.arrTaskFailed_.add(obj);//记录一项失败

        loadStatus.remove(obj);
        iLatestErrorCode_ = iErrorCode;
        if (loadStatus.size() == 0) {
            hideLoading();
            showDialog(iLatestErrorCode_);
        }
    }

    protected synchronized void finishedLoad(Object obj) {
        loadStatus.remove(obj);
        if (this.arrTaskFailed_ != null){
            arrTaskFailed_.remove(obj);
        }
        if (loadStatus.size() == 0) {
            hideLoading();
            if (this.arrTaskFailed_ != null && this.arrTaskFailed_.size() > 0) {
                showDialog(iLatestErrorCode_);
            }
        }
    }

    protected void resetRequireTask(){
        if (arrTaskFailed_ != null){
            arrTaskFailed_.clear();
        }
        bRetryRequire_ = false;
    }

    protected void retryRequire(){

    }

    @Override
    protected Dialog onCreateDialog(int id) {
      //  hideLoading();
        Dialog dialog = null;
        Toast.makeText(this, R.string.network_error, Toast.LENGTH_SHORT).show();
        return dialog;
    }
    
    /**
     * 程序是否在前台运行
     * 
     * @return
     */
	public boolean isAppOnForeground() {
		// 返回一个列表，在设备上运行的应用程序进程
		ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
		String packageName = getApplicationContext().getPackageName();
		List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
		if (appProcesses == null)
			return false;

		for (RunningAppProcessInfo appProcess : appProcesses) {
			// The name of the process that this object is associated with.
			if (appProcess.processName.equals(packageName)&& appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
				return true;
			}
		}
		return false;
	}
	
	public void startActivitySafely(Intent intent) {
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		try {
			startActivity(intent);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "启动异常", Toast.LENGTH_SHORT).show();
		} catch (SecurityException e) {
			Toast.makeText(this, "启动异常", Toast.LENGTH_SHORT).show();
			Log.e("BaseActivity", "无权限 " + intent + ". 确保创建一个相应的活动的主要意图过滤器 "
					+ "这项活动或使用导出的属性.", e);
		}
	}

	
	
	
//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
	//程序不退出，转为后台运行
//		PackageManager pm = getPackageManager();
//		ResolveInfo homeInfo = pm.resolveActivity(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME), 0);
//		if (keyCode == KeyEvent.KEYCODE_BACK) {
//			Log.e(TAG, "onKeyDown 返回按钮");
//			ActivityInfo ai = homeInfo.activityInfo;
//			Intent startIntent = new Intent(Intent.ACTION_MAIN);
//			startIntent.addCategory(Intent.CATEGORY_LAUNCHER);
//			startIntent.setComponent(new ComponentName(ai.packageName, ai.name));
//			startActivitySafely(startIntent);
//			return true;
//		} else
//			return super.onKeyDown(keyCode, event);
//	}
}
